package cn.gzsxt.configuration;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
//@MapperScan(basePackages="cn.gzsxt.mapper",annotationClass=Mapper.class,sqlSessionFactoryRef="sqlSessionFactory")
public class DataConfig {
	
	@Bean
	public static MapperScannerConfigurer getMapperScannerConfigurer() {
		MapperScannerConfigurer scannerConfigurer=new MapperScannerConfigurer();
		scannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
		scannerConfigurer.setBasePackage("cn.gzsxt.mapper");
		scannerConfigurer.setAnnotationClass(Mapper.class);
		return scannerConfigurer;
	}
	@Value(value="${db.driverClassName}")
	private String driverClassName;
	@Value(value="${db.password}")
	private String password;
	@Value(value="${db.url}")
	private String url;


	@Value(value="${db.username}")
	private String username; 
	

	@Bean(name="dataSource")
	public BasicDataSource getBasicDataSource() {
		BasicDataSource basicDataSource=new BasicDataSource();
		basicDataSource.setDriverClassName(driverClassName);
		basicDataSource.setUrl(url);
		basicDataSource.setUsername(username);
		basicDataSource.setPassword(password);
		return basicDataSource;
	}
	

	
	@Bean
	public DataSourceTransactionManager getDataSourceTransactionManager() {
		DataSourceTransactionManager dstm=new DataSourceTransactionManager();
		dstm.setDataSource(this.getBasicDataSource());
		return dstm;
	}
	
	
    @Bean(name="sqlSessionFactory")
	public SqlSessionFactory getSqlSessionFactory() {
		SqlSessionFactoryBean factoryBean=new SqlSessionFactoryBean();

		factoryBean.setDataSource(this.getBasicDataSource());

		try {
			factoryBean.afterPropertiesSet();

			 return factoryBean.getObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


}
